<template>
	<div>
		<div class="handel-header">
			<!-- <el-popover
				v-if=""
				v-model="showProduct"
				placement="bottom"
				width="700"
				style="padding: 0 !important"
				trigger="click"
			>
				<crm-relative
					v-if="showProductView"
					ref="crmrelative"
					crm-type="product"
					:radio="true"
					:createable="item.createable"
					:selected-data="selectedData"
					:show="showProduct"
					@close="showProduct = false"
					@create="handleCreate"
					@changeCheckout="selectInfos"
				/>
				<el-button slot="reference" type="primary" @click="onAdd('product')"
					>添加产品</el-button
				>
			</el-popover> -->
			<el-popover
				v-for="btn in showBtns"
				:key="btn.value"
				v-model="btn.showPopover"
				placement="bottom"
				width="700"
				style="padding: 0 !important"
				trigger="click"
			>
				<crm-relative
					v-if="btn.showView"
					ref="crmrelative"
					:crm-type="btn.value"
					:radio="true"
					:createable="item.createable"
					:selected-data="selectedData"
					:query="query"
					:show="btn.showPopover"
					@close="btn.showPopover = false"
					@create="handleCreate"
					@changeCheckout="selectInfos"
				/>
				<el-button
					slot="reference"
					type="primary"
					@click="onAdd(btn)"
					:disabled="btn.disabled"
					style="margin-right: 5px"
					>{{ btn.label }}</el-button
				>
			</el-popover>
		</div>
		<el-table :data="productList" style="width: 100%">
			<el-table-column prop="name" :label="getTypeText() + '名称'" />
			<el-table-column label="选择计划">
				<template slot-scope="{ row }">
					<el-select v-model="row.planId" @change="updateValue">
						<el-option
							v-for="plan in planOptions"
							:key="plan.guaranteeId"
							:value="plan.guaranteeId"
							:label="plan.name"
						></el-option>
					</el-select>
				</template>
			</el-table-column>
			<el-table-column prop="brandName" label="保险公司" />
			<el-table-column prop="supplierName" label="供应商" />
			<el-table-column
				v-if="disabled == false"
				:width="showEdit ? 150 : 80"
				label="操作"
			>
				<template slot-scope="scope">
					<!-- <el-button v-if="showEdit" @click="editItem(scope.$index)" size="mini">编辑</el-button> -->
					<el-button size="mini" @click="removeItem(scope.$index)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<programAdd
			v-if="showCreateProgram"
			:action="createActionInfo"
			@close="showCreateProgram = false"
			@on-handle="handleEditSuccess"
		/>
		<productAdd
			v-if="showCreateProduct"
			:action="createActionInfo"
			@close="showCreateProduct = false"
			@on-handle="handleEditSuccess"
		/>
	</div>
</template>
<script type="text/javascript">
import objMixin from './objMixin'
import CrmRelative from '@/components/createCom/CrmRelative'
import {
	crmProductQueryById,
	crmProductGetPlan
} from '@/api/customermanagement/product'
export default {
	name: 'XhProduct',
	components: {
		CrmRelative,
		programAdd: () =>
			import('@/views/customermanagement/program/components/programAdd'),
		productAdd: () =>
			import('@/views/customermanagement/product/components/productAdd')
	},
	mixins: [objMixin], // 关联产品
	props: {
		action: Object,
		query: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			popoverType: '',
			showPopover: false, // 展示产品框
			showSelectView: false, // 内容
			planOptions: [],
			productList: [],
			totalPrice: 0,
			discountRate: 0,
			// 创建
			showCreateProgram: false,
			showCreateProduct: false,

			showProgram: false,
			showProduct: false,
			showProgramView: false,
			showProductView: false,
			createActionInfo: {},

			addButtons: {
				product: {
					label: '添加产品',
					value: 'product',
					disabled: false,
					showView: false,
					showPopover: false
				},
				program: {
					label: '添加方案',
					value: 'program',
					disabled: false,
					showView: false,
					showPopover: false
				}
			}
		}
	},
	computed: {
		showEdit() {
			// 编辑 目前仅复制保单情况下 显示
			return this.action.type == 'copy' && this.crmType == 'contract'
		},
		selectedData() {
			const res = {
				program: this.productList,
				product: this.productList
			}
			return res
		},

		showBtns() {
			const { product, program } = this.addButtons
			product.disabled = this.disabled
			program.disabled = this.disabled
			if (this.item.data.formType === 'product') {
				return [product]
			}
			if (this.item.data.formType === 'program') {
				return [program]
			}
			if (this.item.data.formType === 'product-solution') {
				if (this.dataValue.product.length) {
					if (this.dataValue.product[0].productId) {
						program.disabled = true
					} else {
						product.disabled = true
					}
				}
				return [product, program]
			}
		}
	},
	watch: {
		dataValue: {
			handler(val) {
				this.refreshProductList()
				this.getPlanOptions()
			},
			deep: true
		}
	},
	mounted() {
		this.refreshProductList()
		this.getPlanOptions()
	},
	methods: {
		onAdd(btn) {
			btn.showView = true
		},
		handleCreate(data) {
			this.createActionInfo = { type: 'save' }
			if (data === 'product') {
				this.showCreateProduct = true
			} else if (data === 'program') {
				this.showCreateProgram = true
			}
			this.showPopover = false
		},
		async handleEditSuccess() {
			if (this.createActionInfo.type == 'update') {
				this.loading = true
				await crmProductQueryById({ id: this.createActionInfo.id })
					.then((res) => {
						var editedIndex = this.productList.findIndex(
							(p) => p.productId == this.createActionInfo.id
						)
						this.productList.splice(editedIndex, 1, res.data)
					})
					.catch((e) => {})
				this.loading = false
			} else {
				this.refreshProductList()
			}
		},
		/**
		 * 刷新数据
		 */
		refreshProductList() {
			this.productList = this.dataValue.product
			this.totalPrice = this.dataValue.totalPrice
			this.discountRate = this.dataValue.discountRate
		},
		// 获取产品计划
		getPlanOptions() {
			const productId = this.productList[0]?.productId
			crmProductGetPlan({ id: productId }).then(({ data }) => {
				this.planOptions = data
			})
		},
		/** 选中 */
		selectInfos(data) {
			if (data.data) {
				const self = this
				// 2020-09-07 改单选
				self.productList = data.data

				this.updateValue() // 传递数据给父组件
			}
		},
		getShowItem(data) {
			const item = {}
			item.name = data.name
			item.categoryName = data.categoryName
			item.unit = data.unit
			item.price = data.price
			item.salesPrice = data.price
			item.num = 0
			item.discount = 0
			item.subtotal = 0
			item.productId = data.productId
			return item
		},
		// 单价
		salesPriceChange(data) {
			this.verifyNumberValue(data, 'salesPrice')
			const item = data.row

			let discount = ((item.price - item.salesPrice || 0) / item.price) * 100.0
			discount = discount.toFixed(2)
			if (item.discount !== discount) {
				item.discount = discount
			}
			this.calculateSubTotal(item)
			this.calculateToal()
		},
		// 数量
		numChange(data) {
			this.verifyNumberValue(data, 'num')
			const item = data.row
			this.calculateSubTotal(item)
			this.calculateToal()
		},
		// 折扣
		discountChange(data) {
			this.verifyNumberValue(data, 'discount')
			const item = data.row
			let salesPrice =
				(item.price * (100.0 - parseFloat(item.discount || 0))) / 100.0
			salesPrice = salesPrice.toFixed(2)
			if (item.salesPrice !== salesPrice) {
				item.salesPrice = salesPrice
			}
			this.calculateSubTotal(item)
			this.calculateToal()
		},
		// 计算单价
		calculateSubTotal(item) {
			item.subtotal = (item.salesPrice * parseFloat(item.num || 0)).toFixed(2)
		},
		// 计算总价
		calculateToal() {
			let totalPrice = this.getProductTotal()
			totalPrice =
				(totalPrice * (100.0 - parseFloat(this.discountRate || 0))) / 100.0
			this.totalPrice = totalPrice.toFixed(2)
			this.updateValue() // 传递数据给父组件
		},
		/**
		 * 获取产品总价(未折扣)
		 */
		getProductTotal() {
			let totalPrice = 0.0
			for (let i = 0; i < this.productList.length; i++) {
				const item = this.productList[i]
				totalPrice += parseFloat(item.subtotal)
			}
			return totalPrice
		},
		// 总折扣
		rateChange() {
			if (/^\d+\.?\d{0,2}$/.test(this.discountRate)) {
				this.discountRate = this.discountRate
			} else {
				this.discountRate = this.discountRate.substring(
					0,
					this.discountRate.length - 1
				)
			}
			this.calculateToal()
		},
		/**
		 * 总价更改 折扣更改
		 */
		totalPriceChange() {
			if (/^\d+\.?\d{0,2}$/.test(this.totalPrice)) {
				this.totalPrice = this.totalPrice
			} else {
				this.totalPrice = this.totalPrice.substring(
					0,
					this.totalPrice.length - 1
				)
			}
			const totalPrice = this.getProductTotal()
			this.discountRate = (
				100.0 -
				(parseFloat(this.totalPrice) / totalPrice) * 100
			).toFixed(2)
			this.updateValue()
		},
		// 删除操作
		removeItem(index) {
			this.productList.splice(index, 1)
			this.calculateToal()
		},
		// 编辑操作
		editItem(index) {
			// 行点击，获取当前行
			this.createActionInfo = {
				type: 'update',
				id: this.productList[index].productId
			}
			this.isCreate = true
		},
		updateValue() {
			console.log(this.productList)
			this.valueChange({
				product: this.productList,
				totalPrice: this.totalPrice,
				discountRate: this.discountRate
			})
		},
		/**
		 * 验证数据数值是否符合
		 */
		verifyNumberValue(data, field) {
			if (/^\d+\.?\d{0,2}$/.test(data.row[field])) {
				data.row[field] = data.row[field]
			} else {
				data.row[field] = data.row[field].substring(
					0,
					data.row[field].length - 1
				)
			}
		},
		getTypeText() {
			const { popoverType } = this
			if (popoverType === 'product') {
				return '产品'
			} else if (popoverType === 'program') {
				return '方案'
			} else {
				return ''
			}
		}
	}
}
</script>
<style lang="scss" scoped>
.handel-header {
	button {
		float: right;
		margin-bottom: 10px;
	}
}

.el-table ::v-deep thead th {
	font-size: 12px;
}

.el-table ::v-deep tbody tr td {
	font-size: 12px;
}

.handle-footer {
	position: relative;
	font-size: 12px;
	padding: 5px;
	min-height: 50px;
	.discount-title {
		color: #666;
	}
	.total-info {
		position: absolute;
		right: 20px;
		top: 5px;
		.info-yellow {
			color: #fd715a;
		}
	}
}
</style>
